package com.huluobo.a2109mouthdemo.register;

import android.text.TextUtils;

import com.huluobo.a2109mouthdemo.IMApp;
import com.huluobo.a2109mouthdemo.base.BasePresenter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

/**
 * Created by LC on 2023/12/2.
 */
public class RegisterPresenter extends BasePresenter<RegisterContract.View> implements RegisterContract.Presenter {
    @Override
    public void register(String username, String password, String rePassword) {
        if (username.matches(IMApp.REGEX_USERNAME)) {
            if (password.matches(IMApp.REGEX_PASSWORD)) {
                if (TextUtils.equals(password, rePassword)) {
                    if (isAttach()) {
                        getView().onStartRegister();
                        registerEaseMob(username, password);
                    }
                } else {
                    if (isAttach()) {
                        getView().onRePasswordError();
                    }
                }
            } else {
                if (isAttach()) {
                    getView().onPasswordError();
                }
            }
        } else {
            if (isAttach()) {
                getView().onUsernameError();
            }
        }
    }

    private void registerEaseMob(String username, String password) {
        new Thread(() -> {
            try {
                EMClient.getInstance().createAccount(username, password);
                if (isAttach()) {
                    getView().onRegisterSuccess();
                }
            } catch (HyphenateException e) {
                if (e.getErrorCode() == 203) {
                    if (isAttach()) {
                        getView().onRegisterFailed("用户已注册");
                    }
                } else {
                    if (isAttach()) {
                        getView().onRegisterFailed(e.getMessage());
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

    }
}
